import React, { useRef, useCallback } from 'react';
import { t } from '@/locales/i18n';
import { message } from 'antd';

export const useSelectFile = (props?: {
  fileType?: string;
  multiple?: boolean;
  maxCount?: number;
}) => {
  const { fileType = '*', multiple = false, maxCount = 10 } = props || {};

  const SelectFileDom = useRef<HTMLInputElement>(null);
  const openSign = useRef<any>();

  const File = useCallback(
    ({ onSelect }: { onSelect: (e: File[], sign?: any) => void }) => (
      <div className="absolute h-0 w-0 overflow-hidden">
        <input
          ref={SelectFileDom}
          type="file"
          accept={fileType}
          multiple={multiple}
          onChange={(e) => {
            const files = e.target.files;

            if (!files || files?.length === 0) return;

            let fileList = Array.from(files);
            if (fileList.length > maxCount) {
              // toast({
              //   status: 'warning',
              //   title: fileT('select_file_amount_limit', { max: maxCount })
              // });
              message.warning(t('select_file_amount_limit', { max: maxCount }));
              fileList = fileList.slice(0, maxCount);
            }
            onSelect(fileList, openSign.current);

            e.target.value = '';
          }}
        />
      </div>
    ),
    [t, fileType, maxCount, multiple, message],
  );

  const onOpen = useCallback((sign?: any) => {
    openSign.current = sign;
    SelectFileDom.current && SelectFileDom.current.click();
  }, []);

  return {
    File,
    onOpen,
  };
};
